<template>
  <el-dialog :id="target"   :title="dialoginfo.title"
             width="600px"
             @open="handlerOpened"
             :close-on-click-modal="!1"
             :close-on-press-escape="!1"
             @close="close()" :visible.sync="dialoginfo.show">
    <div id="main" :style="{'height':slide_h+'px'}"  style="min-height:400px;">
      <!-- 中间聊天内容区域 -->
      <div  ref="ctx"  style="overflow-y: auto;border-radius: 4px;" :style="{'max-height':ctx_h+'px','height':ctx_h+'px'}"  class="border-ea chat_bg_panel" v-if="dialoginfo.data.sid===$store.getters.getValForKey('currentToId').sid">
        <div  v-for="(y,key) in dialoginfo.data.logs"  :key="key">
          <div  class="p-10">
            <div class="text-center p-tb5" v-if="key==0||(key>1&&((y.sendTime-dialoginfo.data.logs[key-1].sendTime)>$store.state.HEARTBEAT_TIME))" style="right:10px"><span class="chat_bg_time title12">{{proUtil.formatDate(proUtil.getTimeByTimeZone(8,(y.sendTime/1000*1000)),"hh:mm")}}</span></div>
            <div class="p-relative">
              <div class="pull-left w-50 text-right" :class="{'pull-right text-left':y.sid===cid}">
                <div class="c-9 lue title12 breakAll">{{y.sname}}</div>
              </div>
              <div class="overflow breakAll p-lr10" :class="{'text-right':y.sid===cid}">
                <div class="text-left chat_bg chat_txt" style="max-width:300px" :class="{'chat_bg_my':y.sid===cid}" v-text="y.ctx"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 底部输入框 -->
      <div :style="{'height':(slide_h-ctx_h)+'px'}">
        <div style="background-color: #ffffff;height:30px;line-height: 30px;" >
          工具栏 <i class="el-icon-picture-outline cursor title14 c-00AEEF" onclick="alert('敬请期待')"></i>
        </div>
        <div :style="{'height':(slide_h-ctx_h-76)+'px'}">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 4}"
            placeholder="请输入内容"
            v-model="msg">
          </el-input>
        </div>
        <div style="background-color: #ffffff;height:35px;line-height: 35px;" class="text-right">
          <el-button size="small" @click="close()" type="danger">关 闭</el-button>
          <el-button :disabled="msg==''" size="small" @click="tosend()" type="primary">发 送</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>
  import IMMessage from '@/utils/im/IMMessage';
  export default {
    name: "imService111",
    props:['dialoginfo'],
    data() {
      return {
        target:"imPanel",
        visible: false,
        navinfo: {
          title: '在线客服',
          leftText: '返回',
          leftIcon: '',
          leftLink: '',
          rightText: '',
          rightIcon: '',
          rightLink: 'showpop'
        },
        slide_h: (window.document.body.offsetHeight*0.65).toFixed(0) ,
        ctx_h: (window.document.body.offsetHeight*0.4).toFixed(0),
        cmdLen:this.$store.getters.getValForKey("cmdLen"),
        CMD:this.$store.getters.getValForKey("CMD"),
        CMDHander:this.$store.getters.getValForKey("CMDHander"),
        CMDReverse:{},
        msg: "",
        cid:'s'+this.$store.getters.getUserInfo.id,
      }
    },
    methods: {
      handlerOpened(){
      },
      init(){
        if(this.$store.state.ws==null){
          this.$router.go(-1);
          // this.proUtil.msgInfo("初始化异常",1);
          return;
        }
        this.initCMDReverse();
        this.$store.state.ws.onmessage = (event, ws) => {
          var arrayBuffer = event.data;
          // console.log('receive data: ', arrayBuffer, ws)
          var uint8array = null;
          var firstbyte = new Uint8Array(arrayBuffer, 0, 2);
          var firstchar = new TextDecoder('utf-8').decode(firstbyte);
          var isZipped = false;
          var isZippedStr = '';
          if (firstchar.indexOf('x') != -1) {
            // 压缩过的
            isZipped = true;
            isZippedStr = '(zipped)';
            var zipedUint8array = new Uint8Array(arrayBuffer, 2);
            uint8array = pako.ungzip(zipedUint8array);
          } else {
            uint8array = new Uint8Array(arrayBuffer);
          }
          var data = new TextDecoder('utf-8').decode(uint8array);
          console.log('receive data' + isZippedStr + ': ' + data)
          if (!data || data.length < this.cmdLen) {
            console.error('data wrong' + isZippedStr + ', the data length must be >= ' + this.cmdLen, data);
            return;
          }
          var commandstr = data.substr(0, this.cmdLen);
          console.log(commandstr);
          var commandName = this.CMDReverse[commandstr];
          if (!commandName) {
            console.error('commandstr is ' + commandstr + isZippedStr + ', but con not find commandName');
            return;
          }
          if (!this.CMDHander[commandName]) {
            console.error('can not found siteImBsHandler, commandName is ' + commandName + isZippedStr);
            return;
          }
          if (data.length > this.cmdLen) {
            var bodyStr = data.substr(this.cmdLen);
            console.log('received:' + commandName + isZippedStr + '\r\n, body string is :' + bodyStr);
            var bodyObj = null;
            try {
              bodyObj = JSON.parse(bodyStr);
              console.log(bodyObj);
            } catch (error) {
              console.error(
                'can not parse to object, commandName is ' +
                commandName +
                isZippedStr +
                ', body string is ' +
                bodyStr
              );
              return;
            }
            // console.log("received " + commandName + ", body string is :" + bodyStr);
            this.CMDHander[commandName](this.$store.state.ws, event, commandName, bodyStr, bodyObj,this.$store);
          }
        };
        // this.joingroup();
        // this.getCustomList();
        this.$refs.ctx.scrollTop = this.$refs.ctx.scrollHeight;
      },
      initCMDReverse(){
        for (var cmdName in this.CMD) {
          var commandValue = this.CMD[cmdName];
          this.CMDReverse[this.formatCommand(commandValue)] = cmdName;
        }
        console.log(this.CMDReverse);
      },
      tosend(){
        if(this.$store.getters.getValForKey("currentToId")==""){
          return;
        }
        this.sendInfo(
          this.CMD.P2P_CHAT_REQ,
          new IMMessage(
            this.$store.getters.getValForKey("currentToId").sid,
            this.$store.getters.getUserInfo.id,
            this.msg,
            this.$store.getters.getValForKey("currentToId").sname,
            this.$store.getters.getUserInfo.userName
          )
        );
      },
      // joingroup(groupId){
      //   this.$toast.loading({
      //     mask: true,
      //     duration:300,
      //     message: '连接客服...'
      //   });
      //   this.sendInfo(this.CMD.JOIN_GROUP_REQ,new IMMessage(groupId==null?"":groupId,this.$store.getters.getUserInfo.id,""));
      // },
      getCustomList(){
        //获取客服列表
        this.$toast.loading({
          mask: true,
          duration:300,
          message: '连接客服...'
        });
        this.sendInfo(this.CMD.ALL_CHAT_ROMM_REQ,new IMMessage("",this.$store.getters.getUserInfo.id,""));
      },
      sendInfo(command, bodyObj) {
        if(!this.$store.state.ws||this.$store.state.ws.readyState!=1){
          console.error("ws状态不正确");
          clearTimeout(this.clock);
          return;
        }
        var commandname = this.CMDReverse[command];
        var str = command;
        if (bodyObj) {
          str = command + JSON.stringify(bodyObj);
        }
        console.log('准备发送 ' + commandname + ":'" + str + "'");
        var uint8array = new TextEncoder().encode(str);
        this.$store.state.ws.send(uint8array.buffer);
        this.msg="";
      },
      formatCommand(command){
        var commandstr = command + "";
        if (commandstr.length < this.cmdLen) {
          var gap = this.cmdLen - commandstr.length;
          var supplystr = "";
          for (var index = 0; index < gap; index++) {
            supplystr += "0";
          }
          if (command < 0) {
            commandstr = "-" + supplystr + commandstr.substring(1);
          } else {
            commandstr = supplystr + commandstr;
          }
        }
        return commandstr;
      },
      close() {
        this.$store.state.currentToId="";
        console.log( this.$store.getters.getValForKey("currentToId"));
        this.$emit('changedialogshow');
      },
    },
    beforeCreate: function () {
    },
    created: function () {
    },
    beforeMount: function () {
    },
    mounted: function () {
      this.$nextTick(function(){
        this.init();
        this.$refs.ctx.scrollTop = this.$refs.ctx.scrollHeight;
      })
    },
    updated: function () {
      this.$nextTick(function(){
        this.$refs.ctx.scrollTop = this.$refs.ctx.scrollHeight;
      })
    },
    activated: function () {
    },
    deactivated: function () {
    },
    beforeDestroy: function () {
      // if(this.$store.getters.getUserInfo!=null){
      //   // this.sendInfo(this.CMD.LEAVE_GROUP_REQ,new IMMessage("",this.$store.getters.getUserInfo.id,""));
      //   this.$store.state.ws.removeEventListener('message', function (event) {
      //     console.log('Message from server ', event.data);
      //   });
      // }
    },
    destroyed: function () {
    },
    errorCaptured: function (err, vm, info) {
    }
  }
</script>
<style scoped>
  #imPanel>>>.el-dialog__header{
    padding:10px 20px;
  }
</style>
